package com.zmj.framework.handler.exception;

import com.zmj.framework.exception.limit.LimitException;
import com.zmj.framework.response.ResponseCode;
import com.zmj.framework.response.Result;
import io.github.resilience4j.bulkhead.BulkheadFullException;
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.IllegalStateTransitionException;
import io.github.resilience4j.circuitbreaker.ResultRecordedAsFailureException;
import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LimitExceptionControllerAdvice {

    @ExceptionHandler(LimitException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result<Void> handleLimitException(LimitException ex) {
        return ExceptionMapperUtil.buildBody(ex,ResponseCode.LIMIT);
    }

    @ExceptionHandler(RequestNotPermitted.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result<Void> handleRequestNotPermitted(RequestNotPermitted ex) {
        return ExceptionMapperUtil.buildBody(ex,ResponseCode.LIMIT);
    }

    @ExceptionHandler(BulkheadFullException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result<Void> handleBulkheadFullException(BulkheadFullException ex) {
        return ExceptionMapperUtil.buildBody(ex,ResponseCode.LIMIT);
    }

    @ExceptionHandler(CallNotPermittedException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result<Void> handleCallNotPermittedException(CallNotPermittedException ex) {
        return ExceptionMapperUtil.buildBody(ex,ResponseCode.LIMIT);
    }

    @ExceptionHandler(IllegalStateTransitionException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result<Void> handleIllegalStateTransitionException(IllegalStateTransitionException ex) {
        return ExceptionMapperUtil.buildBody(ex,ResponseCode.LIMIT);
    }

    @ExceptionHandler(ResultRecordedAsFailureException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result<Void> handleResultRecordedAsFailureException(ResultRecordedAsFailureException ex) {
        return ExceptionMapperUtil.buildBody(ex,ResponseCode.LIMIT);
    }

}
